const axios = require('axios')
const ora = require('ora');
const Inquirer = require('inquirer')
const path = require('path')

const {
  promisify
} = require('util');
let ncp = require('ncp');
ncp = promisify(ncp);

// var Git = require("nodegit");


let downloadGitRepo = require('download-git-repo');
downloadGitRepo = promisify(downloadGitRepo);
const {
  downloadDirectory
} = require('./constants');
// 获取仓库列表
const fetchRepoList = async () => {
  // 获取当前组织中的所有仓库信息，这个仓库中存放的都是项目模版
  const {
    data,
  } = await axios.get('https://gitee.com/api/v5/users/yl114/repos');
  return data;
};

const download = async (repo, projectName) => {
  let api = `https://gitee.com/yl114/${repo}`; // 下载项目 

  const dest = `${downloadDirectory}/${repo}`; // 将模板下载到对应的目录中 
  console.log(dest, api);
  const spinner = ora('download template .....').start();
  // https://github.com/Tie-Dan/tdsp-cli.git
  try {
    await downloadGitRepo(api, `../${projectName}`);
    spinner.succeed()
  } catch (error) {
    spinner.fail('download template fail .....')
  }
  // const spinner = ora('download template .....').start();
  // try {
  //   await Git.Clone(`https://gitee.com/yl114/${repo}.git`, `../${projectName}`);
  //   spinner.succeed()
  // } catch (error) {
  //   spinner.fail('download template fail .....')
  // }
  return dest; // 返回下载目录
};

module.exports = async (projectName) => {
  const spinner = ora('fetching template .....').start();
  let repos = await fetchRepoList();
  spinner.succeed(); // 结束loading
  repos = repos.map((item) => item.name);

  const {
    repo,
  } = await Inquirer.prompt({
    name: 'repo', // 获取选择后的结果
    type: 'list', // 什么方式显示在命令行
    message: 'please choise a template to create project', // 提示信息
    choices: repos, // 选择的数据
  });
  console.log(repo);
  download(repo, projectName)
  // await ncp(download(repo), path.join(path.resolve(__dirname), projectName));

}